package de.justphil.tcg.tcgserver.game.states;

import org.slf4j.Logger;

import de.justphil.tcg.tcgserver.game.GameManager;
import de.justphil.tcg.tcgserver.game.domain.Player;
import de.justphil.tcg.tcgserver.game.helpers.GameHelper;
import de.justphil.tcg.tcgserver.websockets.TCGWebSocket;
import de.justphil.tcg.tcgserver.websockets.messages.MessageSubject;
import de.justphil.tcg.tcgserver.websockets.messages.TCGMessage;
import de.justphil.tcg.tcgserver.websockets.util.MessageValidator;
import static de.justphil.tcg.tcgserver.commons.logging.TCGLogging.*;

public class WaitingForPlayerInteraction extends GameState {
	private static final Logger log = logger(WaitingForPlayerInteraction.class);

	@Override
	protected void progress(GameManager gameManager, TCGWebSocket socket, TCGMessage msg, String data) {
		if (MessageSubject.isQuitSubject(msg)) {
			// graceful disconnect
			GameHelper.gracefullyDisconnectPlayer(gameManager, socket);
		}
		else if (MessageSubject.isProgressSubject(msg)) {
			// progress game
			handleProgressMessage(gameManager, socket, msg);
		}
		else {
			assert false : "State 'WaitingForPlayerInteraction' only allows 'game-q' and 'game-p' messages!";
			log.info("State 'WaitingForPlayerInteraction' only allows 'game-q' and 'game-p' messages!");
		}
	}
	
	private void handleProgressMessage(GameManager gameManager, TCGWebSocket socket, TCGMessage msg) {
		log.debug("handleProgressMessage()");
		
		if (gameManager.isResumeRequired() && MessageValidator.isValidResumeMessage(msg)) {
			log.debug("Resume Message!");
			gameManager.unsetResumeRequired(gameManager.getPlayerByWebSocket(socket).getIndex());
			
			if (!gameManager.isResumeRequired()) {
				gameManager.getGame().onResume();
			}
			else {
				log.info("Another 'resume' is required in order to resume.");
			}
		}
		else {
			log.debug("Slot Selected Message!");
			Player thisPlayer = gameManager.getPlayerByWebSocket(socket);
			if (thisPlayer.equals(gameManager.getActivePlayer()) && MessageValidator.isValidSlotSelectedMessage(msg)) {
				Player opponent = gameManager.getOpponent(thisPlayer);
				
				assert opponent != null : "Player's opponent is null!";
				
				gameManager.getGame().onSlotSelected(opponent.getIndex(), msg.getProgressFragment().getSlot());
			}
			else {
				log.info("Player is not the active player or his message is not valid.");
			}
		}
		
		log.debug("handleProgressMessage() -> about to return!");
	}

}
